package com.sita.cfmoto.interact.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sita.cfmoto.R;
import com.sita.cfmoto.my.activity.NoticeActivity;
import com.sita.cfmoto.rest.RestClient;
import com.sita.cfmoto.rest.model.Active;
import com.sita.cfmoto.rest.model.Inform;
import com.sita.cfmoto.rest.model.Member;
import com.sita.cfmoto.rest.model.MemberStatusResponse;
import com.sita.cfmoto.rest.model.RestResponse;
import com.sita.cfmoto.rest.model.request.ApplicationActiveRequest;
import com.sita.cfmoto.rest.model.request.FetchApplicationListRequest;
import com.sita.cfmoto.rest.model.request.FetchMemberStatusRequest;
import com.sita.cfmoto.rest.model.response.ApplicationResponse;
import com.sita.cfmoto.rest.model.response.MemberResponse;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.ui.view.ResizableImageView;
import com.sita.cfmoto.utils.AccountUtils;
import com.sita.cfmoto.utils.CircleTransform;
import com.sita.cfmoto.utils.DateUtils;
import com.squareup.picasso.Picasso;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class ActiveDetailActivity extends Activity {
    private final int MEMBER_STATUS_UNKNOWN = -1;
    private final int MEMBER_STATUS_NO_REQUEST = 0;
    private final int MEMBER_STATUS_WAITING = 1;
    private final int MEMBER_STATUS_NO_APPROVED = 2;
    private final int MEMBER_STATUS_APPROVED = 3;
    @Bind(R.id.active_img)
    ResizableImageView activeImg;
    @Bind(R.id.active_theme_txt)
    TextView activeTheme;
    @Bind(R.id.active_sign_txt)
    TextView activeSign;
    @Bind(R.id.active_time_txt)
    TextView activeTime;
    @Bind(R.id.active_application_state)
    TextView activeApplicationState;
    @Bind(R.id.active_proceed_state)
    TextView activeProceedState;
    @Bind(R.id.active_address)
    TextView activeAddress;
    @Bind(R.id.active_organ)
    TextView activeOrgan;
    @Bind(R.id.active_join_num)
    TextView activeJoinNum;
    @Bind(R.id.active_application_num)
    TextView activeApplicationNum;
    @Bind(R.id.comment_content)
    TextView activeContent;
    @Bind(R.id.share_btn)
    Button activeShareButton;
    @Bind(R.id.active_members_list)
    RecyclerView activeMemberList;
    @Bind(R.id.active_application_list)
    RecyclerView activeApplicationList;
    @Bind(R.id.active_application_layout)
    RelativeLayout applicationLayout;
    @Bind(R.id.active_members_show_list)
    ImageView showList;
    @Bind(R.id.active_application_show_list)
    ImageView showApplicationList;
    @Bind(R.id.active_detail_refresh)
    SwipeRefreshLayout refreshActiveDetail;

    MemberListAdapter mMemberListAdapter;
    MemberListAdapter mApplicationListAdapter;
    private Active active;
    private int mMemberStatus = MEMBER_STATUS_UNKNOWN;
    private boolean isRefresh = false;
    private ArrayList<Member> mMembers = new ArrayList<>();
    private ArrayList<Inform> mApplicationList = new ArrayList<>();

    @OnClick(R.id.btn_share_towx)
    void onClickShareToWX() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_active_detail);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        if (intent != null) {
            active = (Active) intent.getSerializableExtra("active");
            Picasso.with(GlobalContext.getGlobalContext()).load(active.cover.isEmpty() ? null : active.cover).placeholder(R.drawable.official_dynamic_default_icon)
                    .into(activeImg);

            activeTheme.setText(GlobalContext.getGlobalContext().getString(R.string.active_theme, active.title));
            activeSign.setText(GlobalContext.getGlobalContext().getString(R.string.active_sign,
                    DateUtils.shortDate(active.registerStartTime),
                    DateUtils.shortDate(active.registerEndTime)));
            activeTime.setText(GlobalContext.getGlobalContext().getString(R.string.active_time,
                    DateUtils.shortDate(active.campaignStartTime),
                    DateUtils.shortDate(active.campaignEndTime)));
            activeAddress.setText(GlobalContext.getGlobalContext().getString(R.string.active_address, active.deptAddr, active.arriAddr));
            activeOrgan.setText(active.nickName);
            activeJoinNum.setText(GlobalContext.getGlobalContext().getString(R.string.active_join_num, active.members));
            activeContent.setText(active.content);

            updateActiveStatus();
            updateButtonStatus();
            fetchMemberStatus();
            initMemberList();
            fetchMemberList();
        }

        refreshActiveDetail.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!isRefresh) {
                    isRefresh = true;
                    updateActiveStatus();
                    updateButtonStatus();
                    fetchMemberStatus();
                    fetchMemberList();
                }
            }
        });
    }

    @OnClick(R.id.cancel)
    void onClickBack() {
        this.finish();
    }

    @OnClick({R.id.active_join_layout, R.id.active_members_show_list, R.id.active_members_list})
    void onClickJoinPeople() {
        startActivity(MemberListActivity.newIntent(this, mMembers, false));
    }

    @OnClick({R.id.active_application_layout, R.id.active_application_show_list})
    void onClickApplicationPeople() {
        startActivity(NoticeActivity.newIntent(this, mApplicationList));
    }

    void doShare() {
        Intent intent = new Intent();
        intent.setClass(ActiveDetailActivity.this, ActiveShareActivity.class);
        intent.putExtra("active", active);
        startActivity(intent);
    }

    void doApplication() {
//        ToastUtils.show(this, "申请加入");
        ApplicationActiveRequest request = new ApplicationActiveRequest();
        request.userId = AccountUtils.getInstance().getAccountID();
        request.campaignId = active.campaignId;
        RestClient.getRestNormalService().applicationActive(request, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (response.getStatus() == 200 && restResponse.mErrorCode.equals("0")) {
                    Log.d("share", "application ok");
                    // TODO: 2016/8/31  update button status;
                    mMemberStatus = MEMBER_STATUS_WAITING;
                    updateButtonStatus();
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    void updateJoinedNumber(int number) {
        activeJoinNum.setText(getString(R.string.active_join_num, number));
        showList.setVisibility(number > 0 ? View.VISIBLE : View.INVISIBLE);
    }

    void updateApplicationNumber(int number) {
        activeApplicationNum.setText(getString(R.string.active_application_num, number));
        showApplicationList.setVisibility(number > 0 ? View.VISIBLE : View.INVISIBLE);
    }

    void showNotStartApplication() {
        ToastUtils.show(this, getString(R.string.my_active_application_not_start_yet));
    }

    void showNotStartActive() {
        ToastUtils.show(this, getString(R.string.my_active_not_start_yet));
    }

    void initMemberList() {
        LinearLayoutManager layoutManager
                = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        activeMemberList.setLayoutManager(layoutManager);

        // publisher
        if (active.userId.equals(AccountUtils.getInstance().getAccountID())) {
            applicationLayout.setVisibility(View.VISIBLE);
            activeApplicationList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
            updateApplicationNumber(0);
        } else {
            applicationLayout.setVisibility(View.GONE);
        }
    }

    void updateActiveStatus() {
        long current = System.currentTimeMillis();
        long applicationStart = DateUtils.convertDateTime(active.registerStartTime);
        long applicationEnd = DateUtils.convertDateTime(active.registerEndTime);
        long activeStart = DateUtils.convertDateTime(active.campaignStartTime);
        long activeEnd = DateUtils.convertDateTime(active.campaignEndTime);
        if (current < applicationStart) {
            activeApplicationState.setText(getResources().getString(R.string.my_active_application_not_start_yet));
        } else if (current > applicationEnd) {
            activeApplicationState.setText(getResources().getString(R.string.my_active_application_over));
        } else {
            activeApplicationState.setText(getResources().getString(R.string.my_active_application_ing));
        }

        if (current < activeStart) {
            activeProceedState.setText(getResources().getString(R.string.my_active_not_start_yet));
        } else if (current > activeEnd) {
            activeProceedState.setText(getResources().getString(R.string.my_active_over));
        } else {
            activeProceedState.setText(getResources().getString(R.string.my_active_proceeding));
        }
    }

    void updateButtonStatus() {
        long current = System.currentTimeMillis();
        long applicationStart = DateUtils.convertDateTime(active.registerStartTime);
        long applicationEnd = DateUtils.convertDateTime(active.registerEndTime);
        long activeStart = DateUtils.convertDateTime(active.campaignStartTime);
        long activeEnd = DateUtils.convertDateTime(active.campaignEndTime);
        if (AccountUtils.getInstance().getAccountID().equals(active.userId)) {
            if (current > activeEnd) {
                activeShareButton.setVisibility(View.GONE);
            } else if (current > activeStart) {
                activeShareButton.setText(getResources().getString(R.string.my_active_share));
                activeShareButton.setVisibility(View.VISIBLE);
                activeShareButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        doShare();
                    }
                });

            } else {
                activeShareButton.setText(getResources().getString(R.string.my_active_share));
                activeShareButton.setVisibility(View.VISIBLE);
                activeShareButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showNotStartActive();
                    }
                });
            }

        } else {
            if (current > activeEnd) {
                activeShareButton.setVisibility(View.GONE);
            } else if (current < applicationStart) {
                activeShareButton.setText(getResources().getString(R.string.my_active_application));
                activeShareButton.setVisibility(View.VISIBLE);
                activeShareButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showNotStartApplication();
                    }
                });
            } else if (current > applicationStart && current < applicationEnd) {
                // TODO: 2016/8/31 check member status
                if (mMemberStatus == MEMBER_STATUS_NO_REQUEST) {
                    activeShareButton.setText(getResources().getString(R.string.my_active_application));
                    activeShareButton.setVisibility(View.VISIBLE);
                    activeShareButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            doApplication();
                        }
                    });
                } else if (mMemberStatus == MEMBER_STATUS_WAITING) {
                    activeShareButton.setText(getResources().getString(R.string.my_active_approve_waiting));
                    activeShareButton.setVisibility(View.VISIBLE);
                } else if (mMemberStatus == MEMBER_STATUS_APPROVED) {
                    activeShareButton.setText(getResources().getString(R.string.my_active_approved_success));
                    activeShareButton.setVisibility(View.VISIBLE);
                } else if (mMemberStatus == MEMBER_STATUS_NO_APPROVED) {
                    activeShareButton.setText(getResources().getString(R.string.my_active_approved_fail));
                    activeShareButton.setVisibility(View.VISIBLE);
                } else if (mMemberStatus == MEMBER_STATUS_UNKNOWN) {
                    activeShareButton.setVisibility(View.GONE);
                }
            } else if (current > activeStart) {
                // TODO: 2016/8/31 check memeber status
                if (mMemberStatus == MEMBER_STATUS_APPROVED) {
                    activeShareButton.setText(getResources().getString(R.string.my_active_share));
                    activeShareButton.setVisibility(View.VISIBLE);
                    activeShareButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            doShare();
                        }
                    });
                } else {
                    activeShareButton.setVisibility(View.GONE);
                }
            }
        }
    }

    void fetchMemberList() {
        RestClient.getRestNormalService().fetchActiveMemberList(Long.valueOf(active.campaignId), new Callback<MemberResponse>() {
            @Override
            public void success(MemberResponse memberResponse, Response response) {
                if (response.getStatus() == 200 && memberResponse.mErrorCode.equals("0")) {
                    refreshActiveDetail.setRefreshing(false);
                    isRefresh = false;
                    Log.d("fetch member list", "fetch member list");
                    // fake data
                    // get avatars and then notify
                    if (memberResponse.members != null && memberResponse.members.size() > 0) {
                        if (mMemberListAdapter == null) {
                            mMembers.addAll(memberResponse.members);
//                            保留6个
                            mMemberListAdapter = new MemberListAdapter(memberResponse.members.size() > 6 ?
                                    memberResponse.members.subList(0, 6) :
                                    memberResponse.members);
                            activeMemberList.setAdapter(mMemberListAdapter);
                            mMemberListAdapter.notifyDataSetChanged();
                            updateJoinedNumber(mMembers.size());
                        }

                    } else {
                        updateJoinedNumber(0);
                    }


                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });

        if (AccountUtils.getInstance().getAccountID().equals(active.userId)) {
            FetchApplicationListRequest request = new FetchApplicationListRequest();
            request.activeId = Long.valueOf(active.campaignId);

            RestClient.getRestNormalService().fetchApplicationList(request, new Callback<ApplicationResponse>() {
                @Override
                public void success(ApplicationResponse applicationResponse, Response response) {
                    Log.d("fetch application list", "fetch application list");
                    if (response.getStatus() == 200 && applicationResponse.mErrorCode.equals("0")
                            && applicationResponse.applicationList != null &&
                            applicationResponse.applicationList.size() > 0) {
                        if (mApplicationListAdapter == null) {
                            mApplicationList.addAll(applicationResponse.applicationList);
//                            保留6个
                            List<Member> members = new ArrayList<>();
                            int count = 0;
                            for (Inform inform : mApplicationList
                                    ) {
                                if (++count > 6) {
                                    break;
                                }
                                Member m = new Member();
                                m.avatar = inform.avatar;
                                m.nickName = inform.nickName;
                                m.userId = inform.informFromId;
                                members.add(m);
                            }
                            mApplicationListAdapter = new MemberListAdapter(members);
                            activeApplicationList.setAdapter(mApplicationListAdapter);
                            mApplicationListAdapter.notifyDataSetChanged();
                            updateApplicationNumber(mApplicationList.size());
                        }
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    Log.d("fetch member list", "fetch member list error");
                }
            });
        }
    }

    void fetchMemberStatus() {
        FetchMemberStatusRequest request = new FetchMemberStatusRequest();
        request.userId = Long.valueOf(AccountUtils.getInstance().getAccountID());
        request.campaignId = Long.valueOf(active.campaignId);
        RestClient.getRestNormalService().fetchMemberStatus(request, new Callback<MemberStatusResponse>() {
            @Override
            public void success(MemberStatusResponse memberStatusResponse, Response response) {
                if (response.getStatus() == 200 && memberStatusResponse.mErrorCode.equals("0")) {
                    refreshActiveDetail.setRefreshing(false);
                    mMemberStatus = memberStatusResponse.mData;
                    updateButtonStatus();
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(ActiveDetailActivity.this).onActivityResult(requestCode, resultCode, data);
    }

    class MemberListAdapter extends RecyclerView.Adapter<MemberListAdapter.ViewHolder> {
        private List<Member> mMemberList = new ArrayList<>();

        public MemberListAdapter(List<Member> members) {
            super();
            this.mMemberList = members;

        }

        @Override
        public int getItemCount() {
            return mMemberList.size();
        }

        @Override
        public long getItemId(int position) {
            return super.getItemId(position);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            if (TextUtils.isEmpty(mMemberList.get(position).avatar)) return;
            Picasso.with(GlobalContext.getGlobalContext()).load(mMemberList.get(position).avatar)
                    .placeholder(R.drawable.default_head_icon)
                    .transform(new CircleTransform())
                    .centerCrop()
                    .fit()
                    .into(holder.activeImg);
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_active_member_list, parent, false);
            return new ViewHolder(view, parent.equals(activeMemberList));
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            @Bind(R.id.active_member_avatar)
            ImageView activeImg;

            public ViewHolder(View view, boolean isFromMemberList) {
                super(view);
                ButterKnife.bind(this, view);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isFromMemberList) {
                            onClickJoinPeople();
                        } else {
                            onClickApplicationPeople();
                        }
                    }
                });
            }
        }
    }

}
